import sys, os
from Cookie import SimpleCookie
import time as timepkg, glob as globpkg
import random as randompkg 
import errno
from LogUtil import Logger
from TimeOutUtil import TimeOut

MSG501 = "Status: 501 Not Implemented\r\nContent-Length: 0\r\nContent-Type: text/plain\r\n\r\n"
MSG404 = "Status: 404 Not Found\r\nContent-Length: 0\r\nContent-Type: text/plain\r\n\r\n"
MSG0LEN = "Content-Length: 0\r\nContent-Type: text/plain\r\n\r\n"

DEBUG = True

defaultuser = "shafiq"

putLogger = None
getLogger = None
errorLogger = None

timeOut = TimeOut()

#logHelper = Logger(defaultuser, "stacklog", Logger.STDMODE, Logger.GET_Request)

def writeFileToStdout(name):
    fileName = open(name, "rb")
    while True:
        next = fileName.read(4096)
        if not next:
            break
        sys.stdout.write(next)
    fileName.close()
    
def writeStdinToFile(name, mode = "wb"):
    fileHandle = open(name, mode)
    while True:
        next = sys.stdin.read(4096)
        if not next:
            break
        fileHandle.write(next)
    fileHandle.close()
    
def writeToOutput(text):
    sys.stdout.write(text)

def GetContentType(name):
    contentType = ''
    if name.endswith(".m3u8"):
        contentType = "application/vnd.apple.mpegurl"
    elif name.endswith(".ts"):
        contentType = "video/mpeg"
    elif name.endswith(".jpg"):
        contentType = "image/jpeg"
    elif name.endswith(".key"):
        contentType = "application/binary"
    return contentType

def Getsize(name):
    try:
        return os.path.getsize(name)
    except:        
        return 0

def GetHttpCookie():
        try:
            return SimpleCookie(os.environ["HTTP_COOKIE"])
        except:
            cookie = SimpleCookie()
            cookie["user"] = defaultuser
            
            os.environ["HTTP_COOKIE"] = str(cookie)
            return cookie

def GetUser():
    existcookie = GetHttpCookie()
    user = existcookie["user"].value
    if user is None:
        user = defaultuser
    return user
    
def GetModifyTime(name):
    try:
        return os.path.getmtime(name)
    except:
        return 0

def DeleteFile(name, doLog = False):
    try:
        os.remove(name)
        if doLog:
            putLogger.logthis("Successfully removed " + name, Logger.PUT_Request)
    except OSError, e:
        putLogger.logthis(name + ": " + os.strerror(e.errno), Logger.PUT_Request)
        if e.errno != errno.ENOENT: #if error occurred due to some reason other than "No such file" 
            sys.stderr.write("Failed to remove " + name + " \n")
            sys.stderr.write(name + ": " + os.strerror(e.errno))
            if doLog:
                putLogger.logthis("Failed to remove " + name, Logger.PUT_Request)

def writeHeaderToOutput(name):
    writeToOutput("Content-Length: %d\r\nContent-Type: %s\r\n\r\n" % 
                             (Getsize(name), GetContentType(name)))

def strContains(text, pattern):
    if text.find(pattern) == -1:
        return False
    return True

def SequenceNumber(mov_ts):
    splitRequest = mov_ts.split("-")
    temp = splitRequest[2]
    temp = temp.rstrip(".ts")
    return int(temp)

def GetLatest(m3u8Req):
    names = globpkg.glob("%s-*" % m3u8Req)
    (date, name) = max((GetModifyTime(name), name) for name in names)
    return name

def GetCurrentTime():
    return timepkg.time()

def GetRandInt(min, max):
    return randompkg.randint(min, max)

def Rename(old, new):
    try:
        os.rename(old, new)
    except:
        sys.stderr.write("Failed trying to rename from " + str(old) + " to " + str(new))

def FileExists(fileName):
    return os.path.exists(fileName)

def NextAvailableRequest(lastRequest):
    lastSeq = SequenceNumber(lastRequest)
    for i in range(0, 15, 1):
        newSeq = lastSeq + i
        newRequest = lastRequest.replace(str(lastSeq), str(newSeq))
        if FileExists(newRequest):
            lastRequest = newRequest
            break
    return lastRequest